package com.jinyuanchun.learnjava.service.impl;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.jinyuanchun.learnjava.mapper.PmsProjectMapper;
import com.jinyuanchun.learnjava.dao.PmsProject;
import com.jinyuanchun.learnjava.service.PmsProjectService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class PmsProjectServiceImpl implements PmsProjectService{

    @Resource
    private PmsProjectMapper pmsProjectMapper;

    @Override
    public int deleteByPrimaryKey(String subprojectId) {
        return pmsProjectMapper.deleteByPrimaryKey(subprojectId);
    }

    @Override
    public int insert(PmsProject record) {
        return pmsProjectMapper.insert(record);
    }

    @Override
    public int insertSelective(PmsProject record) {
        return pmsProjectMapper.insertSelective(record);
    }

    @Override
    public PmsProject selectByPrimaryKey(String subprojectId) {
        return pmsProjectMapper.selectByPrimaryKey(subprojectId);
    }

    @Override
    public int updateByPrimaryKeySelective(PmsProject record) {
        return pmsProjectMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(PmsProject record) {
        return pmsProjectMapper.updateByPrimaryKey(record);
    }

    @Override
    public int insertOrUpdateByList(List<PmsProject> pmsProjects) {
        List<String> subs = new ArrayList<>();
        for(PmsProject item: pmsProjects){
            String sub = item.getSubprojectId();
            subs.add(sub);
        }
        Map<String,PmsProject> exists = pmsProjectMapper.existInList(subs);
        List<PmsProject> inserts = getInsert(exists,pmsProjects);
        List<PmsProject> updates = getUpdate(exists,pmsProjects);

        int iFlag = pmsProjectMapper.insertBatch(inserts);
        int uFlag = pmsProjectMapper.updateBatch(updates);
        return 1;
    }

    private List<PmsProject> getUpdate(Map<String, PmsProject> exists, List<PmsProject> pmsProjects) {
        List<PmsProject> result = new ArrayList<>();
        for(PmsProject item:pmsProjects){
            String sub = item.getSubprojectId();
            if (!exists.containsKey(sub)){
                result.add(item);
            }
        }
        return result;
    }

    private List<PmsProject> getInsert(Map<String, PmsProject> exists, List<PmsProject> pmsProjects) {
        List<PmsProject> result = new ArrayList<>();
        for(PmsProject item:pmsProjects){
            String sub = item.getSubprojectId();
            if (exists.containsKey(sub)){
                result.add(item);
            }
        }
        return result;
    }


}
